import Vue from 'vue'
import Vuex from 'vuex'
import {api} from '../config'
import request from '../utils/api'
import router from '../router'
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        access_token: sessionStorage.getItem('access_token'),
        user: null,
        loading:false,
    },
    mutations: {
        token (state,payload) {
            // 变更状态
            state.access_token = payload.access_token
            sessionStorage.setItem('access_token',state.access_token)
        },
        setLoading(state,payload){
            state.loading = payload.loading;
        },
        profile (state,payload){
            state.user = payload.profile
        }
    },
    actions : {
        login({ dispatch, commit }, data){
             commit('setLoading',{loading:true})
            request.post(api.login,data).then((res)=>{
                console.log(res);
                commit('setLoading',{loading:false})
                if(res.status){
                        let access_token = res.data.access_token
                        commit('token',{access_token:access_token})
                        router.push("/dashboard")
                        dispatch('profile');
                }
            }).catch((error)=>{
                 commit('setLoading',{loading:false})
            })
        },
        profile({commit,state}){
            request.get(api.profile).then((res)=>{
                if(res.status){
                    commit('profile',{profile:res.data})
                }
            }).catch((error)=>{

            })
        },
        logout({commit,state}){
            commit('token',{access_token:null})
            router.push('/login')
        }
    }
})

export default store